﻿using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Util;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorizeController : ControllerBase
    {
        private readonly IUserService _userService;
        public AuthorizeController(IUserService service)
        {
            _userService = service;
        }

        [HttpPost("Login")]
        public async Task<ActionResult<ApiResult>> Login(string username, string password)
        {
            string pwd = MD5Helper.MD5Encrypt32(password);
            var user = await _userService.QueryAsync(t=>t.UserName == username && t.Password == pwd);
            if(user != null)
            {
                //登陆成功
                var claims = new Claim[]
                {
                        new Claim(ClaimTypes.Name, user[0].Name),
                        new Claim("Id", user[0].Id.ToString()),
                        new Claim("UserName", user[0].UserName)
                        //不能放敏感信息 
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SDMC-CJAS1-SAD-DFSFA-SADHJVF-VF"));
                //issuer代表颁发Token的Web应用程序，audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5266",
                    audience: "http://localhost:5266",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return ApiResultHelper.Success(jwtToken);
            }
            else
            {
                return ApiResultHelper.Error("登录失败");
            }
        }
    }
}
